<?php
/**
 * wiki basic counter init
 * @author tangyiwan
 */

ini_set('display_errors', 1);
error_reporting(-1);
ini_set('memory_limit', '512M');
require_once '/data/wwwroot/g_vendor/autoload.php';

use Biz\cache\wiki\WikiBasicCounter;
use Biz\cache\wiki\WikiFavorite;
use Biz\model\wiki\Wiki as mWiki;
use Biz\model\wiki\WikiBasic as mWikiBasic;

$page = 1;
$pageSize = 200;
$basicInfos = [];
do {
    $limit = [($page - 1) * $pageSize, $pageSize];
    $basicInfos = mWikiBasic::selectByWhere([
        'LIMIT' => $limit,
    ]);
    foreach ($basicInfos as $row) {
        $favoriteNum = 0;
        $clickBuyNum = 0;
        $definedNum = 0;
        $relateNum = 0;
        if ($row['basic_state'] != mWikiBasic::STATE_DEL) {
            $wikiInfos = mWiki::selectByWhere(['basic_id' => $row['id'], 'status[!]' => mWiki::STATUS_DEL]);
            if ($wikiInfos) {
                $wikiIds = array_column($wikiInfos, 'id');
                $favCounterList = WikiFavorite::getCounter($wikiIds);
                foreach ($wikiInfos as $wikiInfo) {
                    $favCount = isset($favCounterList[$wikiInfo['id']]) ? $favCounterList[$wikiInfo['id']] : 0;
                    $favoriteNum += $favCount;
                    $clickBuyNum += $wikiInfo['click_buy_num'];
                    $definedNum += $wikiInfo['defined_increment'];
                    $relateNum += $wikiInfo['relate_num'];
                }
            }
        }
        var_dump('设置basic counter', ['id' => $row['id'], 'fav' => $favoriteNum, 'buy' => $clickBuyNum, 'defined' => $definedNum, 'relate' => $relateNum]);
        WikiBasicCounter::setFavoriteNum($row['id'], $favoriteNum);
        WikiBasicCounter::setClickBuyNum($row['id'], $clickBuyNum);
        WikiBasicCounter::setDefinedNum($row['id'], $definedNum);
        WikiBasicCounter::setRelateNum($row['id'], $relateNum);
    }
    $page++;
} while ($basicInfos);

